<template>
  <div class="service-records-list">
    <div class="page-header">
      <h2>服务执行记录管理</h2>
      <el-button type="primary" @click="handleAdd" v-if="authStore.userRole !== '用户'">
        <el-icon><Plus /></el-icon>
        添加服务记录
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="预约编号">
          <el-input
            v-model="searchForm.appointmentId"
            placeholder="请输入预约编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="服务人员">
          <el-input
            v-model="searchForm.staffId"
            placeholder="请输入服务人员编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="searchForm.startTimeStart"
            type="datetime"
            placeholder="开始时间"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="searchForm.startTimeEnd"
            type="datetime"
            placeholder="结束时间"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="recordId" label="服务记录编号" width="120" />
        <el-table-column prop="appointmentId" label="关联预约编号" width="120" />
        <el-table-column prop="staffId" label="服务人员编号" width="120" />
        <el-table-column prop="startTime" label="实际开始时间" width="180" />
        <el-table-column prop="endTime" label="实际结束时间" width="180" />
        <el-table-column prop="itemsUsed" label="使用物品" min-width="180" show-overflow-tooltip />
        <el-table-column prop="serviceDetails" label="服务详情" min-width="180" show-overflow-tooltip />
        <el-table-column prop="costDetails" label="费用明细" min-width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right" v-if="authStore.userRole !== '用户'">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { serviceRecordsApi } from '@/api'
import type { ServiceRecords, ServiceRecordsQuery } from '@/types'
import { handlePageResponse } from '@/utils/pagination'

const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const loading = ref(false)
const tableData = ref<ServiceRecords[]>([])
const searchForm = reactive<ServiceRecordsQuery>({
  appointmentId: undefined,
  staffId: undefined,
  startTimeStart: '',
  startTimeEnd: ''
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params: ServiceRecordsQuery = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    
    const response = await serviceRecordsApi.getPage(params)
    
    // 使用工具函数统一处理分页响应
    const pageData = handlePageResponse<ServiceRecords>(response)
    
    // 更新表格数据和分页信息
    tableData.value = pageData.records
    pagination.total = pageData.total
    pagination.current = pageData.current
    pagination.size = pageData.size
  } catch (error) {
    console.error('获取服务记录数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    appointmentId: undefined,
    staffId: undefined,
    startTimeStart: '',
    startTimeEnd: ''
  })
  pagination.current = 1
  fetchData()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  fetchData()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchData()
}

// 添加服务记录
const handleAdd = () => {
  router.push('/service-records/add')
}

// 编辑服务记录
const handleEdit = (row: ServiceRecords) => {
  router.push(`/service-records/update/${row.recordId}`)
}

// 删除服务记录
const handleDelete = async (row: ServiceRecords) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除服务记录"${row.recordId}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await serviceRecordsApi.delete(row.recordId!)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchData()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除服务记录失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 初始化
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.service-records-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 